package com.hanxiaozhang.filter.body;



import com.hanxiaozhang.constant.Constant;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 功能描述: <br>
 * 〈HttpServletRequestWrapperFilter〉
 *
 * @Author:hanxinghua
 * @Date: 2020/7/4
 */
@Configuration
@WebFilter(filterName = "httpServletRequestWrapperFilter", urlPatterns = "/*")
public class HttpServletRequestWrapperFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        ServletRequest requestWrapper = null;

        String contentType = request.getContentType();

        if (contentType != null && contentType.contains(Constant.APP_JSON)) {

            if (request instanceof HttpServletRequest) {
                requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
            }

            if (null == requestWrapper) {
                chain.doFilter(request, response);
            } else {
                chain.doFilter(requestWrapper, response);
            }

        }else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {
    }
}
